package com.cskaoyan.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 为register6请求提供的类型转换器 String → Date
 * @author stone
 * @date 2021/12/31 10:03
 */
@Component
public class String2DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String string) {
        //如果我就解析yyyy-MM-dd
        SimpleDateFormat simpleDateFormat = null;
        Date date = null;
        try {
            //自定义的类型转换业务，大家可以根据业务需求写更丰富的转换业务
            if (string.contains("-") && string.length() == 10) {
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            } else if (string.length() == 19) {
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            } else {
                simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            }
            date = simpleDateFormat.parse(string);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
